from rest_framework import serializers
from django.contrib.auth import get_user_model
from .models import WechatAuth, SmsVerification
from rest_framework_simplejwt.serializers import TokenRefreshSerializer as BaseTokenRefreshSerializer
from rest_framework_simplejwt.tokens import UntypedToken
from rest_framework_simplejwt.exceptions import TokenError
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from django.apps import apps

User = get_user_model()


class WechatLoginSerializer(serializers.Serializer):
    """微信小程序登录序列化器"""
    
    code = serializers.CharField(required=True, help_text='微信登录临时凭证')
    user_info = serializers.JSONField(required=False, help_text='用户信息（可选）')
    phone = serializers.CharField(required=False, allow_blank=True, help_text='手机号（可选，用于绑定手机号）')
    
    class Meta:
        fields = ['code', 'user_info', 'phone']


class SmsVerificationSerializer(serializers.Serializer):
    """短信验证码序列化器"""
    
    phone = serializers.CharField(required=True, help_text='手机号')
    purpose = serializers.ChoiceField(
        choices=SmsVerification.Purpose.choices, 
        default=SmsVerification.Purpose.LOGIN,
        help_text='用途：' + ' | '.join([f"{choice[0]}={choice[1]}" for choice in SmsVerification.Purpose.choices])
    )
    
    class Meta:
        fields = ['phone', 'purpose']


class SmsLoginSerializer(serializers.Serializer):
    """短信登录序列化器"""
    
    phone = serializers.CharField(required=True, help_text='手机号')
    code = serializers.CharField(required=True, min_length=6, max_length=6, help_text='验证码')
    
    class Meta:
        fields = ['phone', 'code']


class TokenRefreshSerializer(BaseTokenRefreshSerializer):
    """令牌刷新序列化器"""
    
    class Meta:
        fields = ['refresh', 'access']


class TokenVerifySerializer(serializers.Serializer):
    """令牌验证序列化器"""
    
    token = serializers.CharField(required=True, write_only=True, help_text='访问令牌')
    
    class Meta:
        fields = ['token']
    
    def validate(self, attrs):
        """验证令牌并自定义返回数据"""
        token_str = attrs['token']
        
        try:
            token = UntypedToken(token_str)
            
            # 检查是否在黑名单中
            if (
                apps.is_installed("rest_framework_simplejwt.token_blacklist")
                and getattr(settings, "SIMPLE_JWT", {}).get("BLACKLIST_AFTER_ROTATION", False)
            ):
                from rest_framework_simplejwt.token_blacklist.models import BlacklistedToken
                
                jti = token.get("jti")
                if BlacklistedToken.objects.filter(token__jti=jti).exists():
                    raise TokenError(_("Token is blacklisted"))
            
            # 自定义返回数据
            return {
                'valid': True,
                'message': 'Token is valid',
                'token_type': token.get('token_type', 'unknown'),
                'user_id': token.get('user_id', None),
                'exp': token.get('exp', None)
            }
        except TokenError as e:
            raise serializers.ValidationError(str(e))
        except Exception as e:
            raise serializers.ValidationError(_("Token is invalid or expired"))


class TokenBlacklistSerializer(serializers.Serializer):
    """令牌黑名单序列化器"""
    
    refresh = serializers.CharField(required=True, help_text='刷新令牌')
    
    class Meta:
        fields = ['refresh']


class UserInfoSerializer(serializers.ModelSerializer):
    """用户信息序列化器"""
    
    class Meta:
        model = User
        fields = ['id', 'phone', 'role', 'avatar', 'company', 'credit_score', 'date_joined', 'last_login']
        read_only_fields = ['id', 'date_joined', 'last_login']